import request from "@/api/request.js";

/**
 * 从响应头中解析文件名
 * @param {string} contentDisposition Content-Disposition 头部
 * @param {string} defaultFilename 默认文件名
 * @returns {string} 解析后的文件名
 */
const parseFilenameFromHeaders = (contentDisposition, defaultFilename) => {
    if (!contentDisposition) return defaultFilename;

    // 尝试匹配 filename*=UTF-8''xxx 或 filename="xxx"
    const filenameMatch = contentDisposition.match(/filename\*?=([^;]+)/i);

    if (filenameMatch && filenameMatch[1]) {
        // 处理 filename*=UTF-8''encodedfilename
        if (filenameMatch[0].toLowerCase().startsWith('filename*=')) {
            // 解码 RFC 5987 格式（UTF-8）
            return decodeURIComponent(filenameMatch[1].replace(/utf-8''/i, ''));
        }
        // 处理 filename="xxx"
        return filenameMatch[1].replace(/["']/g, '');
    }

    return defaultFilename;
};

export async function downloadFileV2(params, url, filename) {
    const response = await request({
        url: url,
        method: 'get',
        responseType: 'blob',
        params: params,
        isDownloadRequest: true
    })
    let filename1 = filename;
    try {
        // 1. 获取文件名
        filename1 = parseFilenameFromHeaders(response.headers['content-disposition'], filename1);

        // 2. 创建 Blob 并下载
        const blob = new Blob([response.data]);
        const url1 = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url1;
        link.download = filename1;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url1);
    } catch (error) {
        console.error('文件下载失败:', error);
        throw error;
    }
}
/**
 * 上传文件 V2
 * @param {Object} formData 表单数据
 * @param {string} url 上传地址
 * @param {Object} options 额外配置
 * @returns {Promise}
 */
export function uploadFileV2(formData, url, options = {}) {
    const config = {
        url: url,
        method: 'post',
        data: formData,
        headers: {
            'Content-Type': 'multipart/form-data',
            ...options.headers
        },
        timeout: options.timeout || 30000,
        onUploadProgress: options.onUploadProgress, // 上传进度回调
        isUploadRequest: true // 标识为上传请求
    };

    const response = request(config)
    if (options.onSuccess) {
        options.onSuccess(response)
    }
    return response;
}